<?php

namespace app\api\controller\yexam;

use app\admin\model\yexam\Fav;
use app\admin\model\yexam\QuestionLog;
use app\common\controller\Api;

/**
 * @ApiSector (试题相关)
 */
class Question extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['easyErrorQuestion','redHotQuestion'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * @ApiTitle (获取试题内容)
     * @ApiSummary (给接口发送试题id，接口返回该试题的选项，答案，解析等等内容,typeId:如果是章节则是章节id，试卷包id则是试卷包id)
     * @ApiParams (name=id,type=integer,required=true,description=试题id)
     * @ApiParams (name=type,type=integer,required=true,description=类型，默认为1 日志类型1=免费，2=章节，3=付费，4=历年，5=模拟，6=正式)
     * @ApiParams (name=typeId,type=integer,required=true,description=类型id,对应的id)
     * @ApiMethod (POST)
     * @throws \think\Exception
     */
    public function info(){
        $id = $this->request->post('id');
        $type = $this->request->post('type',1); // 类型 ,默认为免费
        $typeId = $this->request->post('typeId',1); // 类型id，默认为：免费
        $question = new \addons\yexam\service\Question();
        $data = $question->getQuestion($id,$this->auth->id,$type,$typeId);
        $this->success('请求成功',$data);
    }
    /**
     * @ApiTitle (获取免费试题)
     * @ApiMethod (GET)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     * @ApiParams (name=is_free,type=integer,required=true,description=是否免费)
     * @ApiHeaders (name=token,type=string,required=true,description=token)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function freelist()
    {
        $subjectId  = $this->request->param('subject_id');
        $isFree = $this->request->param('is_free',0);
        $user_id = $this->auth->id;

        //============== 1.查看是否有免费章节
        $unit = new \app\admin\model\yexam\Unit();
        $isFreeUnit = $unit->where('subject_id',$subjectId)->where('is_free',$isFree)->select();
        $questionModel = new \app\admin\model\yexam\Question();
        $unitIds = [];
        if (count($isFreeUnit))
        {
            foreach ($isFreeUnit as $value)
            {
                array_push($unitIds,$value->id);
            }
            $unit_id = implode(',',$unitIds);
            $data = $questionModel
                ->alias("question")
                ->field("question.*,ifnull(log.state,3) as state")
                ->join("yexam_question_log log","question.id=log.question_id and log.user_id=".$user_id,"left")
                ->where('question.unit_id','in',$unit_id)->order("question.type asc,question.id asc")->select();
        }else{
            //============= 无免费章节则显示所有的免费试题
            $data = $questionModel
                ->alias("question")
                ->field("question.*,ifnull(log.state,3) as state")
                ->join("yexam_question_log log","question.id=log.question_id and log.user_id=".$user_id,"left")
                ->where('question.subject_id',$subjectId)->where('question.is_free',$isFree)->order("question.type asc,question.id asc")->select();
        }
        $return = [];
        foreach($data as $v){
            $_return['id'] = $v['id'];
            $_return['state'] = $v['state'] ==3?3:($v['state']==0?1:2);        //1是错 2是对 3是未答过此题
            $return[] = $_return;
        }
        $this->success('',$return,1);
    }
    /**
     * @ApiTitle (定位上次的学习记录)
     * @ApiMethod (POST)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     * @ApiReturnParams  (name=msg,type=string,required=true,sample=请求成功)
     * @ApiReturn  ({'code':'1','msg' : "请求成功"})
     */
    public function position()
    {
        $subjectId = $this->request->post('subject_id');
        $type = $this->request->post("type",-1);
        $where['a.subject_id'] = $subjectId;
        $where['a.user_id'] = $this->auth->id;
        if ($type >= 0){
            $where['a.type'] = $type;
        }
        //获取当前单元已经练习的最后的题目ID
        $logModel = new QuestionLog();
        $data = $logModel
            ->field("a.question_id")
            ->alias("a")
            ->join("yexam_question b","a.question_id=b.id",'inner')
            ->where($where)->order('a.lasttime desc')->find();
        if(empty($data)){ // 说明第一次做题
            $num = 1;
        }else{
            $questionModel = new \app\admin\model\yexam\Question();
            $questionList = $questionModel->field("id")->where(['subject_id'=>$subjectId])->where('is_free',0)->order("type asc,id asc")->select();
            $questionList = $questionList->toArray();
            $num = 1;
            foreach($questionList as $k=>$v){
                $num++;
                if($data['question_id'] == $v['id']){
                    break;
                }
            }
            if($num>count($questionList)){
                $num = 1;
            }
        }
        $this->success('请求成功',$num);
    }
    /**
     * @ApiTitle (定位上次学习记录)
     * @ApiInternal
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bagPosition(){
        $bag_id = $this->request->param('bag_id');
        $bag = \app\admin\model\yexam\Exam::get($bag_id);
        $subjectId = $bag->subject_id;
        //获取当前单元已经练习的最后的题目ID
        $logModel = new QuestionLog();
        $data = $logModel
            ->field("a.question_id")
            ->alias("a")
            ->join("yexam_question b","a.question_id=b.id",'inner')
            ->where(['a.subject_id'=> $subjectId,'user_id'=>$this->auth->id])->order('a.lasttime desc')->find();
        if(empty($data)){ // 说明第一次做题
            $num = 1;
        }else{
            $questionModel = new \app\admin\model\yexam\Question();
            $questionList = $questionModel->field("id")->where(['subject_id'=>$subjectId])->where('is_free',0)->order("type asc,id asc")->select();
            $num = 1;
            foreach($questionList as $k=>$v){
                $num++;
                if($data['question_id'] == $v['id']){
                    break;
                }
            }
            if($num>count($questionList)){
                $num = 1;
            }
        }
        $this->success('请求成功',$num);
    }
    /**
     * @ApiTitle (question ids )
     * @ApiMethod (GET)
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function questionPosition()
    {
        $id = $this->request->param('id');
        $questionModel = new \app\admin\model\yexam\Question();
        $subjectId = $questionModel->where('id',$id)->value('subject_id');
        //获取当前单元已经练习的最后的题目ID
        $logModel = new QuestionLog();
        $data = $logModel
            ->field("a.question_id")
            ->alias("a")
            ->join("yexam_question b","a.question_id=b.id",'inner')
            ->where(['a.subject_id'=> $subjectId,'user_id'=>$this->auth->id])->order('a.lasttime desc')->find();
        if(empty($data)){ // 说明第一次做题
            $num = 1;
        }else{
            $questionModel = new \app\admin\model\yexam\Question();
            $questionList = $questionModel->field("id")->where(['subject_id'=>$subjectId])->where('is_free',0)->order("type asc,id asc")->select();
            $num = 1;
            foreach($questionList as $k=>$v){
                $num++;
                if($data['question_id'] == $v['id']){
                    break;
                }
            }
            if($num>count($questionList)){
                $num = 1;
            }
        }
        $this->success('请求成功',$num);
    }

    /**
     * @ApiTitle (易错试题)
     * @ApiMethod (POST)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     */
    public function easyErrorQuestion(){
        $subjectId = $this->request->post('subject_id');
        $question = new \app\admin\model\yexam\QuestionLog();
        if ($this->request->has('unit')){
            $list = $question->where('subject_id',$subjectId)->field('unit_id,count(id) as num')->group('unit_id')->select();
            foreach ($list as $key => $value){
                $unit = \app\admin\model\yexam\Unit::get($value['unit_id']);
                if (!is_null($unit)){
                    $list[$key]['unit_name'] = $unit->unit_name;
                    $list[$key]['id'] = $value['unit_id'];
                }
            }
            $this->success('请求成功',['data' => $list]);
        }
        if ($this->request->has('question')){
            $page = $this->request->param('page');
            $limit = $this->request->param('limit');
            $unitId = $this->request->param('unit_id',0);
            if ($unitId != 0) $where['unit_id'] = $unitId;
            $where['subject_id'] = $subjectId;
            $list = $question->where($where)->page($page,$limit)->field('question_id')->select();
            foreach ($list as $key => $value){
                $list[$key] = \app\admin\model\yexam\Question::get($value['question_id']);
            }
            $total = $question->where($where)->count();
            $this->success('请求成功',['data' => $list,'total' => $total]);
        }
        $list = $question->where('subject_id',$subjectId)->field('id')->distinct('question_id')->where('state',0)->select();
        $tmp = [];
        foreach ($list as $value)
            $tmp[] = [
                'id' => $value['id'],
                'state' => 3
            ];
        $this->success('请求成功',$tmp);
    }

    /**
     * @ApiTitle (热点试题)
     * @ApiSummary (根据收藏数量来进行获取)
     * @ApiMethod (POST)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     */
    public function redHotQuestion()
    {
        $subjectId = $this->request->post('subject_id');
        $favorite = new Fav();
        if ($this->request->has('unit'))
        {
            $list = $favorite->where('subject_id',$subjectId)->field('unit_id,count(id) as num')->group('unit_id')->select();
            foreach ($list as $key => $value)
            {
                $list[$key]['unit_name'] = \app\admin\model\yexam\Unit::get($value['unit_id'])->unit_name;
                $list[$key]['id'] = $value['unit_id'];
            }
            $this->success('请求成功',[
                'data' => $list
            ]);
        }
        if ($this->request->has("question")){
            $page = $this->request->param('page');
            $limit = $this->request->param('limit');
            $unitId = $this->request->param('unit_id');
            if ($unitId != 0) $where['unit_id'] = $unitId;
            $where['subject_id'] = $subjectId;
            $list = $favorite->where($where)->field('question_id')->page($page,$limit)->select();
            foreach ($list as $key => $value){
                $list[$key] = \app\admin\model\yexam\Question::get($value['question_id']);
            }
            $total = $favorite->where($where)->count();
            $this->success('请求成功',['data' => $list,'total' => $total]);
        }
        $list = $favorite->where('subject_id',$subjectId)->distinct('question_id')->select();
        $tmp = [];
        foreach ($list as $value)
            $tmp[] = [
                'id' => $value['question_id'],
                'state' => 3
            ];
        $this->success('请求成功',$tmp);
    }
    /**
     * @ApiTitle (试题搜索)
     * @ApiSummary (试题检索，进行搜索时需要提供科目id。否则搜索无结果)
     * @ApiParams (name=subject_id,type=integer,required=true,description=科目id)
     * @ApiParams (name=search,type=string,required=true,description=搜索关键字)
     * @ApiParams (name=page,type=integer,required=false,description=页数)
     * @ApiParams (name=limit,type=integer,required=false,description=每页数量，默认20条数据)
     * @ApiMethod (GET)
     */
    public function searchQuestion()
    {
        $search = $this->request->param('search');
        $subjectId = $this->request->param('subject_id');
        $page = $this->request->param('page',1);
        $limit = $this->request->param('limit',20);
        $question = new \app\admin\model\yexam\Question();
        $searchResult = $question->whereLike('question_name',"%{$search}%")
            ->page($page,$limit)->where('subject_id',$subjectId)->select();
        $this->success('请求成功',$searchResult);
    }
}
